package main.java.indi.zyj.coderecord;

public class IslandPerimeter {


    public int islandPerimeter(int[][] grid) {

        int row = grid.length;
        int col = grid[0].length;
        int[][] location = new int[][]{
                {0, 1},
                {1, 0},
                {-1, 0},
                {0, -1}
        };

        int res = 0;        // 记录岛屿周长

        // 遍历整个二维数组，如果当前格子是岛屿，则遍历四周，如果周围有岛屿，则不算周长
        // 否则周长+1
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                if (grid[i][j] == 1) {
                    for (int k = 0; k < location.length; k++) {
                        int nextX = i + location[k][0];
                        int nextY = j + location[k][1];
                        if (nextX < 0 || nextX >= row || nextY < 0 || nextY >=col) {
                            res++;
                        } else if (grid[nextX][nextY] == 0) {
                            res++;
                        }

                    }
                }
            }
        }

        return res;

    }

}
